﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.zmc;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.Zmc.Warehou;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.Zmc.Warehou
{
    public class CreateCleaningOrderCommandHandlers : IRequestHandler<CreateCleaningOrderCommands, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public CreateCleaningOrderCommandHandlers(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }


        /// <summary>
        /// 创建清洗数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(CreateCleaningOrderCommands request, CancellationToken cancellationToken)
        {

            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnums.添加成功;
            result.Msg = "添加成功";
            try
            {
                await db.Ado.BeginTranAsync();  //开启事务
                // 1.创建主清洗记录
                // 创建主记录
                var order = new Cleaningorder
                {
                    DeviceType = request.DeviceType,
                    ProgramType = request.ProgramType,
                    CreateTime =new DateTime(),
                    Duration = request.Duration,
                    WarehousId=1,
                    Result = 1,
                 
                };

                // 插入并获取主表ID
                var orderId = await db.Insertable(order).ExecuteReturnIdentityAsync();


             

                // 处理物品关联
                foreach (var item in request.Items)
                {
                    var stuff = await db.Queryable<Stuff>()
                        .Where(s => s.Stuffbarcode == item.Stuffbarcode)
                        .FirstAsync();

                    if (stuff == null)
                        throw new Exception($"条码[{item.Stuffbarcode}]对应的物资不存在");

                    var relation = new CleaningStuffRelation
                    {
                        CleaningOrderId = orderId,
                        StuffId = stuff.StuffId,
                        Quantity = item.Quantity
                    };

                    await db.Insertable(relation).ExecuteCommandAsync();
                }

                await db.Ado.CommitTranAsync();  // 提交事务
                result.Data = orderId;
                return result;
            }
            catch (Exception ex)
            {
                await db.Ado.RollbackTranAsync();  //回滚事务

                throw;
            }

        }
    }
}
